/**
 * Title:        获取对应的模板信息
 * Company:      泛微软件
 */


package checkWithCondit;

import general.BaseBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.engines.AESFastEngine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.encoders.Hex;
import org.json.JSONObject;

import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.workflow.request.WFLinkInfo;



public class TemplateSteeingCheck extends BaseBean implements checkWithConBase  {

    @Override
    public JSONObject checkData(HashMap dataMap) {
        setRecordSet();
        List resultList = new ArrayList();
        String result = "";

        int requestid = -1;
        int userid = -1;
        int workflowid = -1;
        int curnodeid = -1;
        int formid = -1;
        int ismode = -1;
        String customPage = "";
        int version = 0;
        String syspath = "";
        String scriptStr = "";
        RecordSet fieldattrRs = new RecordSet();
        if(dataMap.get("requestid") == null || dataMap.get("requestid").equals("")){
            result = resultERROR;
            resultList.add("请选择流程请求。");
            return formatReturnJsonCheck(result, resultList, this);
        }
        requestid = Util.getIntValue(Util.null2String(dataMap.get("requestid")),-1);
        userid = Util.getIntValue(Util.null2String(dataMap.get("userid")),-1);
        WFLinkInfo WFLinkInfo = new WFLinkInfo();
        if(userid == -1){
            recordSet.executeSql(" select userid from workflow_currentoperator where id = (select max(id) from workflow_currentoperator where requestid = " + requestid + " and islasttimes = 1)");
            if(recordSet.next()){
                userid = recordSet.getInt("userid");
            }
        }
        curnodeid = WFLinkInfo.getCurrentNodeid(requestid, userid, 1);
        String nodetype=WFLinkInfo.getNodeType(curnodeid);
        RecordSet rs = new RecordSet();
        rs.executeSql("select workflowid,isremark,isreminded,preisremark,id,groupdetailid,nodeid,takisremark,(CASE WHEN isremark=9 THEN '7.5' WHEN (isremark=1 and takisremark=2) THEN '0.9' WHEN (preisremark=1 and takisremark=2) THEN '0.9' ELSE isremark END) orderisremark from workflow_currentoperator where requestid="+requestid+" and userid="+userid+" and usertype=0 order by orderisremark,islasttimes desc ");
        while(rs.next()){
            workflowid = Util.getIntValue(rs.getString("workflowid"));
            String isremark = Util.null2String(rs.getString("isremark"));
            if(isremark.equals("1")||isremark.equals("5") || isremark.equals("7")|| isremark.equals("9") ||(isremark.equals("0")  && !nodetype.equals("3")) ) {
                curnodeid = Util.getIntValue(rs.getString("nodeid"));
                break;
            }
        }
        rs.executeSql("select formid,custompage from workflow_base where id="+workflowid);
        if(rs.next()){
            formid = Util.getIntValue(rs.getString("formid"));
            customPage = Util.null2String(rs.getString("custompage"));
        }
        customPage = !"".equals(customPage) ? customPage : "无";
        rs.executeSql("select ismode from workflow_flownode where nodeid="+curnodeid+ " and workflowid="+workflowid);
        if(rs.next())
            ismode = Util.getIntValue(rs.getString("ismode"));
        boolean hasActive = true;
        try{
            rs.executeSql("select isactive from workflow_nodehtmllayout where nodeid="+curnodeid);
        }catch(Exception e){
            hasActive = false;
        }
        if(ismode == 2){    //Html模式
            String sql = "select version,syspath,scripts from workflow_nodehtmllayout where nodeid="+curnodeid+" and workflowid="+workflowid+" and type=0";
            if(hasActive)   sql += " and isactive=1";
            sql += " order by id desc";
            rs.executeSql(sql);
            if(rs.next()){
                version = Util.getIntValue(rs.getString("version"));
                if(version == 2){
                    scriptStr = rs.getString("scripts");
                    scriptStr = decodeStr(scriptStr);
                }else{
                    syspath = rs.getString("syspath");
                }
            }else{
                ismode = -1;
            }
            result = resultNeedFix;


            resultList.add("流程自定义页面custompage："+ customPage + "");

            resultList.add("代码块内容：<br>"+ scriptStr + "");

            resultList.add("模板文件路径syspath：："+ syspath + "");
            
            sql = "select caltype,fieldid,attrcontent,workflow_billfield.fieldname from workflow_nodefieldattr inner join workflow_billfield on workflow_billfield.id = workflow_nodefieldattr.fieldid where nodeid="+curnodeid+" and formid="+formid;
            fieldattrRs.executeSql(sql);
            while(fieldattrRs.next()){
                resultList.add("字段[" + fieldattrRs.getString("fieldname") + "]存在[" + transType(Util.getIntValue(fieldattrRs.getString("caltype"))) + "]操作["+ fieldattrRs.getString("attrcontent") + "]");
            }
        }else{
            resultList.add("模板类型：非Html模板");
            resultList.add("流程自定义页面custompage："+ customPage + "");
        }
        return formatReturnJsonCheck(result, resultList, this);
    }

    @Override
    public JSONObject fixData(HashMap dataMap) {

        //重新加载DIV
        needReload = "1";
        return checkData(new HashMap());
    }

    @Override
    public String getClassName() {
        return "获取对应的模板信息";
    }

    @Override
    public String getClassDesc() {
        return "根据requestid及userid取对应的模板信息(自定义页面custompage、代码块、字段属性(SQL赋值)等)";
    }

    @Override
    public String getPopupUrl() {
        return "/flowtoolbar/checkWithCondit/RequestAndUser.jsp";
    }

    public String decodeStr(String content) {
        byte[] keybytes = "WEAVER E-DESIGN.".getBytes();
        byte[] iv = "weaver e-design.".getBytes();
        try {
            BufferedBlockCipher engine = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
            engine.init(true, new ParametersWithIV(new KeyParameter(keybytes),iv));
            System.err.println(content);
            byte[] deByte = Hex.decode(content);
            engine.init(false, new ParametersWithIV(new KeyParameter(keybytes),iv));
            byte[] dec = new byte[engine.getOutputSize(deByte.length)];
            int size1 = engine.processBytes(deByte, 0, deByte.length, dec, 0);
            int size2 = engine.doFinal(dec, size1);
            byte[] decryptedContent = new byte[size1 + size2];
            System.arraycopy(dec, 0, decryptedContent, 0,decryptedContent.length);
            return new String(decryptedContent);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    public String transType(int caltype){
        if(caltype == 1)
            return "SQL赋值";
        else if(caltype == 2)
            return "数值计算";
        else if(caltype == 3)
            return "日期时间计算";
        return "";
    }

}



